package db

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	yaml "gopkg.in/yaml.v3"
	"log"
	"os"
)

type Config struct {
	MySql MySql `yaml:"mysql"`
}
type MySql struct {
	Ip       string `yaml:"ip"`
	Port     int    `yaml:"port"`
	UserName string `yaml:"username"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
	Charset  string `yaml:"charset"`
	min      int    `yaml:"min"`
	max      int    `yaml:"max"`
}

var mysqlDb *gorm.DB

func Db() *gorm.DB {
	return mysqlDb
}
func (ms MySql) crate() {
	str := fmt.Sprintf(`%s:%s@(%s:%d)/%s?charset=%s&parseTime=True&loc=Local`,
		ms.UserName, ms.Password, ms.Ip, ms.Port, ms.Database, ms.Charset)
	log.Println(str)
	db, err := gorm.Open("mysql", str)
	if err != nil {
		log.Fatal("mysql数据库连接失败", err)
	}
	defer func(db *gorm.DB) {
		_ = db.Close()
	}(db)
	//设置最大空闲和连接数
	db.DB().SetMaxIdleConns(ms.min)
	db.DB().SetMaxOpenConns(ms.max)
	mysqlDb = db
}

func init() {
	file, err := os.Open("app.yaml")
	if err != nil {
		log.Fatal("获取配置文件异常", err)
	}
	var conf Config
	decoder := yaml.NewDecoder(file)
	_ = decoder.Decode(&conf)
	log.Println(conf)

	conf.MySql.crate()
}
